package com.zrm.zfcrpa.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

@Component
public class HttpUtils {

	private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);



    /**
     * get请求
     * @param params 请求参数
     * @param charset 编码格式
     * @param URL 请求地址
     * @param CONNECTTIMEOUT 连接超时时间，单位：秒
     * @param SOCKETTIMEOUT 通信超时时长，单位：秒
     */
	public static String sendGet(Map<String, String> params, String charset, 
			String URL,int CONNECTTIMEOUT,int SOCKETTIMEOUT
			)
			throws Exception {
		StringBuilder result = new StringBuilder();
		params = params == null ? new HashMap<String,String>() : params;
		StringBuffer paramString = new StringBuffer();
		if(!params.isEmpty()) {
			paramString.append("?");
			params.forEach((key,value) -> {
				paramString.append(key + "=" + value + "&");
			});
			paramString.delete(paramString.length()-1, paramString.length());
		}
		BufferedReader in = null;
		HttpURLConnection conn = null;
		try {
			String finalUrl = URL + paramString.toString();
			logger.info("调度url："+finalUrl);
			URL realUrl = new URL(finalUrl);
			// 打开和URL之间的连接
			conn = (HttpURLConnection) realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");

			//设置GET请求
			conn.setRequestMethod("GET");
			conn.setDoInput(true);
			conn.setDoOutput(false);
			conn.setUseCaches(true);
			// 设置超时时间
			conn.setConnectTimeout(CONNECTTIMEOUT * 1000);
			conn.setReadTimeout(SOCKETTIMEOUT * 1000);

			//连接
			logger.info("HTTP执行请求！");
			conn.connect();
			
			// 得到响应状态码
			int code = conn.getResponseCode();
			if(code == 200) {
				logger.info("HTTP调用edg网关成功！");
				in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
				String line;
				while ((line = in.readLine()) != null) {
					result.append(line);
				}
			}else{
				result.append("网络响应").append(code).append(".");
			}
			return result.toString();
		} catch (SocketTimeoutException e) {
			logger.info("SocketTimeoutException！,异常原因：" + e);
			result.append("SocketTimeoutException");
			throw new SocketTimeoutException();
		} catch (ConnectException e) {
			logger.info("ConnectTimeoutException！,异常原因：" + e);
			result.append("ConnectTimeoutException");
			throw new ConnectException();
		} catch (IOException e) {
			result.append("IOException");
			logger.info("IOException！,异常原因：" + e);
			throw new IOException();
		} catch(Exception e){
			logger.info("Exception！,异常原因：" + e);
			result.append("Exception");
			throw new Exception();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			if(in!=null){
				in.close();
				logger.info("HTTP关闭输入流！");
			}
			if(conn!=null){
				conn.disconnect();
				logger.info("HTTP关闭连接！");
			}
		}
	}
}
